import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/app_theme.dart';
import '../utils/error_handler.dart';
import '../utils/error_display.dart';

class RecordDialog extends StatefulWidget {
  final String recordType;
  final String title;
  final IconData icon;
  final Color iconColor;
  final DateTime? selectedDate;

  const RecordDialog({
    super.key,
    required this.recordType,
    required this.title,
    required this.icon,
    required this.iconColor,
    this.selectedDate,
  });

  @override
  State<RecordDialog> createState() => _RecordDialogState();
}

class _RecordDialogState extends State<RecordDialog> {
  String? _value;
  double _intensity = 5.0;
  final TextEditingController _notesController = TextEditingController();
  final TextEditingController _weightController = TextEditingController();
  final TextEditingController _periodFlowController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: AppTheme.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      title: Row(
        children: [
          Icon(widget.icon, color: widget.iconColor, size: 24),
          const SizedBox(width: 8),
          Text(widget.title, style: AppTheme.titleStyle),
        ],
      ),
      content: SizedBox(
        width: MediaQuery.of(context).size.width * 0.9,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              
              if (widget.recordType == 'period')
                _buildPeriodFlowSelector()
              else if (widget.recordType == 'cramps')
                _buildPainSelector()
              else if (widget.recordType == 'intercourse')
                _buildIntercourseSelector()
              else if (widget.recordType == 'symptoms')
                _buildSymptomsSelector()
              else if (widget.recordType == 'mood')
                _buildMoodSelector()
              else if (widget.recordType == 'discharge')
                _buildDischargeSelector()
              else if (widget.recordType == 'weight')
                _buildWeightInput()
              else if (widget.recordType == 'diary')
                _buildDiaryInput()
              else if (widget.recordType == 'habit')
                _buildHabitSelector()
              else if (widget.recordType == 'plan')
                _buildPlanInput(),
              
              const SizedBox(height: 16),
              
              
              TextField(
                controller: _notesController,
                maxLines: 3,
                decoration: InputDecoration(
                  hintText: '添加备注...',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  contentPadding: const EdgeInsets.all(12),
                ),
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消', style: TextStyle(color: AppTheme.textSecondary)),
        ),
        ElevatedButton(
          onPressed: _saveRecord,
          style: ElevatedButton.styleFrom(
            backgroundColor: AppTheme.primaryColor,
            foregroundColor: AppTheme.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: const Text('保存'),
        ),
      ],
    );
  }

  Widget _buildPeriodFlowSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('经期流量', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: _buildFlowOption('轻', 1),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildFlowOption('中', 2),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildFlowOption('重', 3),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildFlowOption(String label, int value) {
    return GestureDetector(
      onTap: () => setState(() => _value = label),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
          color: _value == label ? AppTheme.primaryColor : AppTheme.background,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: _value == label ? AppTheme.primaryColor : AppTheme.textLight,
          ),
        ),
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: _value == label ? AppTheme.white : AppTheme.textPrimary,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  Widget _buildPainSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('疼痛程度', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        Slider(
          value: _intensity,
          min: 1,
          max: 10,
          divisions: 9,
          activeColor: AppTheme.primaryColor,
          label: _intensity.toString(),
          onChanged: (value) => setState(() => _intensity = value),
        ),
        Text(
          '疼痛指数: ${_intensity.toInt()}',
          style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary),
        ),
      ],
    );
  }

  Widget _buildIntercourseSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('是否使用安全措施？', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: _buildProtectionOption('是', true),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildProtectionOption('否', false),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildProtectionOption(String label, bool value) {
    return GestureDetector(
      onTap: () => setState(() => _value = label),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
          color: _value == label ? AppTheme.primaryColor : AppTheme.background,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: _value == label ? AppTheme.primaryColor : AppTheme.textLight,
          ),
        ),
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: _value == label ? AppTheme.white : AppTheme.textPrimary,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  Widget _buildSymptomsSelector() {
    final symptoms = [
      '头痛', '腰痛', '乳房胀痛', '腹胀', '疲劳', 
      '情绪波动', '失眠', '食欲改变', '恶心', '便秘'
    ];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('症状类型', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: symptoms.map((symptom) {
            return FilterChip(
              label: Text(symptom),
              selected: _value == symptom,
              onSelected: (selected) => setState(() => _value = symptom),
              backgroundColor: AppTheme.background,
              selectedColor: AppTheme.primaryColor.withValues(alpha: 0.2),
              checkmarkColor: AppTheme.primaryColor,
            );
          }).toList(),
        ),
      ],
    );
  }

  Widget _buildMoodSelector() {
    final moods = ['😊', '😐', '😞', '😣', '😭'];
    final moodLabels = ['开心', '一般', '难过', '烦躁', '沮丧'];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('心情状态', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: List.generate(5, (index) {
            return Column(
              children: [
                GestureDetector(
                  onTap: () => setState(() => _value = moods[index]),
                  child: Text(
                    moods[index],
                    style: TextStyle(
                      fontSize: 32,
                      color: _value == moods[index] ? AppTheme.primaryColor : AppTheme.textPrimary,
                    ),
                  ),
                ),
                Text(
                  moodLabels[index],
                  style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary),
                ),
              ],
            );
          }),
        ),
      ],
    );
  }

  Widget _buildDischargeSelector() {
    final dischargeTypes = ['正常', '异常', '有异味', '颜色异常'];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('白带情况', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        Column(
          children: dischargeTypes.map((type) {
            return InkWell(
              onTap: () => _handleDischargeSelection(type),
              child: Container(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: _value == type ? AppTheme.primaryColor : Colors.grey,
                          width: 2,
                        ),
                      ),
                      child: _value == type
                          ? Center(
                              child: Container(
                                width: 10,
                                height: 10,
                                decoration: const BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: AppTheme.primaryColor,
                                ),
                              ),
                            )
                          : null,
                    ),
                    const SizedBox(width: 8),
                    Text(type),
                  ],
                ),
              ),
            );
          }).toList(),
        )
      ],
    );
  }

  void _handleDischargeSelection(String type) {
    setState(() => _value = type);
  }

  Widget _buildWeightInput() {
    return TextField(
      controller: _weightController,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        labelText: '体重 (kg)',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        suffixText: 'kg',
      ),
    );
  }

  Widget _buildDiaryInput() {
    return TextField(
      controller: _notesController,
      maxLines: 5,
      decoration: InputDecoration(
        labelText: '日记内容',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  Widget _buildHabitSelector() {
    final habits = ['运动', '喝水', '早睡', '营养补充', '冥想', '阅读'];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('好习惯', style: AppTheme.bodyStyle),
        const SizedBox(height: 8),
        ...habits.map((habit) => CheckboxListTile(
          title: Text(habit),
          value: false,
          onChanged: (value) {},
        )),
      ],
    );
  }

  Widget _buildPlanInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextField(
          decoration: InputDecoration(
            labelText: '计划名称',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
        const SizedBox(height: 8),
        TextField(
          decoration: InputDecoration(
            labelText: '计划时间',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            suffixIcon: Icon(Icons.calendar_today, color: AppTheme.primaryColor),
          ),
        ),
      ],
    );
  }

  Future<void> _saveRecord() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final date = widget.selectedDate ?? DateTime.now();
      final dateKey = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
      
      Map<String, dynamic> recordData = {
        'type': widget.recordType,
        'value': _value ?? '',
        'intensity': _intensity,
        'notes': _notesController.text,
        'weight': _weightController.text,
        'timestamp': date.millisecondsSinceEpoch,
      };
      
      await prefs.setString('record_$dateKey', recordData.toString());
      
      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('${widget.title}记录已保存'),
            backgroundColor: AppTheme.primaryColor,
          ),
        );
      }
    } catch (e) {
      // 错误处理
      final errorHandler = ErrorHandler();
      final appError = errorHandler.handleError(e, '_saveRecord');
      
      if (mounted) {
        // 显示错误提示
        ErrorDisplay.showErrorWithRetry(
          context,
          appError,
          _saveRecord,
        );
      }
    }
  }

  @override
  void dispose() {
    _notesController.dispose();
    _weightController.dispose();
    _periodFlowController.dispose();
    super.dispose();
  }
}